import orgService from "@/api/services/system/orgService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import {
	DownOutlined,
	MinusOutlined,
	MinusSquareOutlined,
	PlusOutlined,
	PlusSquareOutlined,
	RightOutlined,
} from "@ant-design/icons";
import { Button, Card, Drawer, Form, Input, Modal, Select, Space, Table, message } from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useMemo, useState } from "react";
import { BasicStatus } from "#/enum";

interface Organization {
	id: string;
	name: string;
	parentId: string;
	description: string;
	children?: Organization[];
}

export default function OrganizationPage() {
	const [form] = Form.useForm();
	const [data, setData] = useState<Organization[]>([]);
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [modalTitle, setModalTitle] = useState("");
	const [editingRecord, setEditingRecord] = useState<Organization | null>(null);
	const [selectedNode, setSelectedNode] = useState<Organization | null>(null);
	const [loading, setLoading] = useState(false);

	// 表格列配置
	const columns: ColumnsType<Organization> = [
		{
			title: "名称",
			dataIndex: "name",
			key: "name",
		},
		{
			title: "描述",
			dataIndex: "description",
			key: "description",
		},
		{
			title: "操作",
			key: "operation",
			width: 280,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleEdit(record)}>
						编辑
					</Button>
					<Button type="link" onClick={() => handleAddSub(record)}>
						添加子节点
					</Button>
					<Button type="link" danger onClick={() => handleDelete(record)}>
						删除
					</Button>
				</Space>
			),
		},
	];

	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
	// 状态管理
	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => String(col.key!)),
	);
	// 处理过滤后的列配置
	const filteredColumns = useMemo(() => {
		return [
			// 显示选中的列
			...columns.filter(
				(col) => selectedValues.includes(String(col.key)) || col.key === "operation", // 始终包含操作列
			),
		].sort((a, b) => {
			// 保持原始顺序
			const originalIndex = columns.findIndex((c) => c.key === a.key);
			const targetIndex = columns.findIndex((c) => c.key === b.key);
			return originalIndex - targetIndex;
		});
	}, [selectedValues]);

	// 获取组织列表
	const fetchOrgList = async () => {
		try {
			setLoading(true);
			const res = await orgService.queryAll();
			setData(res);
		} catch (error) {
			message.error("获取组织列表失败");
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		fetchOrgList();
	}, []);

	// 打开新增根节点模态框
	const handleAddRoot = () => {
		setModalTitle("新增根节点");
		setEditingRecord(null);
		form.resetFields();
		setDrawerVisible(true);
	};

	// 打开新增子节点模态框
	const handleAddSub = (record: Organization) => {
		setModalTitle("新增子节点");
		setEditingRecord(record);
		form.resetFields();
		setDrawerVisible(true);
	};

	// 打开编辑模态框
	const handleEdit = (record: Organization) => {
		setModalTitle("编辑节点");
		setEditingRecord(record);
		form.setFieldsValue(record);
		setDrawerVisible(true);
	};

	// 删除节点
	const handleDelete = async (record: Organization) => {
		Modal.confirm({
			title: "确认删除",
			content: "确定要删除该节点吗？删除后将无法恢复。",
			onOk: async () => {
				try {
					await orgService.deleteById(record.id);
					message.success("删除成功");
					fetchOrgList();
				} catch (error) {
					message.error("删除失败");
				}
			},
		});
	};

	// 提交表单
	const handleSubmit = async () => {
		try {
			const values = await form.validateFields();
			if (modalTitle === "编辑节点") {
				await orgService.update({
					...values,
					id: editingRecord?.id,
				});
				message.success("更新成功");
			} else {
				await orgService.add({
					...values,
					parentId: modalTitle === "新增根节点" ? "0" : editingRecord?.id,
				});
				message.success("创建成功");
			}
			setDrawerVisible(false);
			fetchOrgList();
		} catch (error) {
			message.error("操作失败");
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingRecord(null);
		form.resetFields();
	};

	return (
		<Card>
			<div className="flex justify-between mb-4">
				{/* 操作按钮 */}
				<div className="flex gap-2">
					<Button type="primary" icon={<PlusOutlined />} onClick={handleAddRoot}>
						新增根节点
					</Button>
				</div>
				<TableToolbar
					onRefresh={fetchOrgList}
					onSizeChange={setTableSize}
					columns={columns}
					selectedValues={selectedValues}
					onColumnChange={setSelectedValues}
				/>
			</div>
			<Table
				columns={filteredColumns}
				size={tableSize}
				dataSource={data}
				rowKey="id"
				loading={loading}
				pagination={false}
				expandable={{
					expandIcon: ({ expanded, onExpand, record }) => {
						if (!record.children || record.children.length === 0) {
							return null; // 如果没有子节点，不显示展开图标
						}
						return (
							<span onClick={(e) => onExpand(record, e)} className="mr-2">
								{expanded ? <MinusOutlined /> : <PlusOutlined />}
							</span>
						);
					},
				}}
			/>

			<Drawer
				title={modalTitle}
				width={480}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						<Button type="primary" onClick={() => handleSubmit()}>
							确定
						</Button>
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} layout="horizontal">
					{modalTitle === "新增子节点" && (
						<Form.Item label="父节点">
							<Input value={editingRecord?.name} disabled />
						</Form.Item>
					)}
					<Form.Item name="name" label="名称" rules={[{ required: true, message: "请输入名称" }]}>
						<Input />
					</Form.Item>
					<Form.Item name="description" label="描述">
						<Input.TextArea />
					</Form.Item>
					<Form.Item name="status" label="状态" initialValue={BasicStatus.ENABLE}>
						<Select
							options={[
								{ label: "启用", value: BasicStatus.ENABLE },
								{ label: "禁用", value: BasicStatus.DISABLE },
							]}
						/>
					</Form.Item>
				</Form>
			</Drawer>
		</Card>
	);
}
